import { useFocusEffect, useRouter } from "expo-router";
import { useCallback, useState } from "react";
import { FlatList, Image, Text, TouchableOpacity, View } from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";

type Employee = {
  nickName: string;
  imei: string;
  heartRate?: number;
  headImg?: string;
  lat?: number;
  lon?: number;
};

async function fetchEmployees(): Promise<Employee[]> {
  const res = await fetch("http://192.168.1.137:8000/getCardList", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ memberId: 100503 }),
  });
  const data = await res.json();
  // 假设后端返回的数据结构为 { list: Employee[] }
  return data.message || [];
}

function EmployeeItem({ item }: { item: Employee }) {
  const router = useRouter();
  const handlePress = () => {
    if (item.lat && item.lon) {
      router.push({
        pathname: "/map",
        params: {
          lat: item.lat,
          lon: item.lon,
          name: item.nickName,
          headImg: item.headImg || "https://placehold.co/60x60", // 添加头像参数
        },
      });
    } else {
      alert("该员工没有位置信息");
    }
  };
  return (
    <TouchableOpacity onPress={handlePress}>
      <View
        style={{
          flexDirection: "row",
          alignItems: "center",
          paddingVertical: 12,
          paddingHorizontal: 16,
          backgroundColor: "#fff",
          borderRadius: 12,
          marginBottom: 12,
          shadowColor: "#000",
          shadowOpacity: 0.05,
          shadowOffset: { width: 0, height: 2 },
          shadowRadius: 4,
          elevation: 2,
        }}
      >
        {/* 左侧头像 */}
        <Image
          source={{ uri: item.headImg || "https://placehold.co/60x60" }}
          style={{ width: 48, height: 48, borderRadius: 24, marginRight: 12 }}
        />

        {/* 中间信息 */}
        <View style={{ flex: 1 }}>
          <Text style={{ fontSize: 16, fontWeight: "600" }}>{item.nickName}</Text>
          <Text style={{ fontSize: 12, color: "#6B7280" }}>IMEI: {item.imei}</Text>
          {/* <Text style={{ fontSize: 12, color: "#6B7280", marginTop: 2 }}>
          工作时长: {item.workHours?.toFixed(1) || 0} 小时
        </Text> */}
        </View>

        {/* 右侧状态 */}
        <View style={{ alignItems: "flex-end" }}>
          <Text
            style={{
              fontSize: 14,
              fontWeight: "600",
              color: "green",
            }}
          >
            ♥ {item.heartRate} bpm
          </Text>
          <Text
            style={{
              fontSize: 14,
              color: "orange",
            }}
          >
            SpO₂ "--"
          </Text>
        </View>
      </View>
    </TouchableOpacity>
  );
}

export default function EmployeeList() {
  const [employees, setEmployees] = useState<Employee[]>([]);
  const [loading, setLoading] = useState(true);

useFocusEffect(
  useCallback(() => {
    setLoading(true);
    fetchEmployees()
      .then(setEmployees)
      .finally(() => setLoading(false));
  }, [])
);

  return (
    <SafeAreaView style={{ flex: 1, backgroundColor: "#F3F4F6", padding: 16 }}>
      {loading ? (
        <Text style={{ textAlign: "center", marginTop: 40 }}>加载中...</Text>
      ) : (
        <FlatList
          data={employees}
          keyExtractor={(item) => item.imei}
          renderItem={({ item }) => <EmployeeItem item={item} />}
          contentContainerStyle={{ paddingBottom: 20 }}
        />
      )}
    </SafeAreaView>
  );
}
